package com.hyc.Serializer;

import com.hyc.message.MessageType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author 冷环渊
 * @date 2025/6/4 11:34
 * @description MyDecoder
 */
public class MyDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        short messageType = byteBuf.readShort();
        if (messageType != MessageType.REQUEST.getCode() && messageType != MessageType.RESPONSE.getCode()) {
            throw new RuntimeException("未知类型 暂不支持");
        }
        short serializerType = byteBuf.readShort();
        Serializer serializer = Serializer.getSerializerByCode(serializerType);
        if (serializer == null) {
            throw new RuntimeException("未知序列化器");
        }
        //反序列化
        int length = byteBuf.readInt();
        byte[] res = new byte[length];
        byteBuf.readBytes(res);
        Object object = serializer.deserializer(res, messageType);
        list.add(object);
    }
}
